package com.zyy.seckill.exception;

import com.zyy.seckill.vo.RespBean;
import com.zyy.seckill.vo.RespEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 *
 *      全局异常处理器
 * @Author: zyy
 * @DateTime: 2021/10/3 21:01
 */
@RestControllerAdvice //设置全局捕获异常
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)// 标注范围异常处理发的范围
    public RespBean ExceptionHandler(Exception e){

        if (e instanceof GlobalException){// GlobalException继承了runtimeException
            GlobalException ex = (GlobalException) e;
            return RespBean.error(ex.getRespEnum());

        }else if (e instanceof BindException){ //如果属于绑定异常就抛出
            BindException ex = (BindException) e;
            RespBean respBean = RespBean.error(RespEnum.BIND_ERROR);
            respBean.setMessage("参数校验异常: "+ex.getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespEnum.FAILED);
    }
}
